<?php namespace app\system\controller;

use houdunwang\dir\Dir;
use houdunwang\request\Request;
use houdunwang\route\Controller;
use houdunwang\validate\Validate;
use system\model\Admin;


/*
 * 安装
 * Class Install
 */
class Install extends Controller{

	public function __construct()
	{
		$this->isInstalled();
	}

	//是否已经安装
	public function isInstalled()
	{
		if(is_file('lock.php'))
		{
			die(view('isInstalled'));
		}
	}

	//版权信息
	public function copyright ()
	{

		//此处书写代码...
		return view();
	}

	//环境检测
	public function environmental()
	{
		$data['server_software'] = $_SERVER['SERVER_SOFTWARE'];
		$data['php_version'] = PHP_VERSION;
		$data['pdo'] = extension_loaded('pdo');
		$data['gd'] = extension_loaded('gd');
		$data['curl'] = extension_loaded('curl');
		$data['openssl'] = extension_loaded('openssl');
		//dd(version_compare('7.1.2','5.4','>'));//true
		//dd(version_compare('7.1.2','8.4','>'));//false

		return view('',compact('data'));
	}


	//连接数据库
	public function database()
	{
		if(IS_AJAX){
			//接收post数据
			$post = Request::post();
			//p($post);die;
			//验证
			Validate::make([
				['host','required','请输入主机地址',Validate::MUST_VALIDATE],
				['user','required','请输入用户名',Validate::MUST_VALIDATE],
				['password','required','请输入密码',Validate::MUST_VALIDATE],
				['database','required','请输入数据库',Validate::MUST_VALIDATE],
				['prefix','required','请输入表前缀',Validate::MUST_VALIDATE],
			]);
			//连接数据库
			$dsn = "mysql:host={$post['host']};dbname={$post['database']}";
			try{
				$pdo = new \PDO($dsn,$post['user'],$post['password']);
				Dir::create('data');
				file_put_contents('data/database.php',"<?php\r\nreturn ".var_export($post,true).";\r\n?>");
			}catch (\Exception $exception){
				return $this->error("数据库连接失败：".$exception->getMessage());
			}
			return $this->success('数据库连接成功');
		}
		return view();
	}

	public function tables()
	{
		//创建数据表
		cli('hd migrate:make');
		cli('hd seed:make');
		//写入管理员数据
		$model = new Admin();
		$model['admin_username'] = 'admin';
		$model['admin_password'] = '$2y$10$B9eab4.qiqFF.d1ny/92Iu9q3ScCI/b1umWrub5.6V1tVfgvagkZ.';
		$model->save();
		go('finish');
	}
	//完成安装
	public function finish()
	{
		//生成lock.php文件
		touch('lock.php');
//		file_put_contents('lock.php','');
		return view();
	}
}
